package com.example.androidhive;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

//import com.example.androidhive.Adreszpalca.DownloadTask;
//import com.example.androidhive.MainActivity.ParserTask;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class Polozenie extends Activity {
	// Progress Dialog
	private ProgressDialog pDialog;

	JSONParser jsonParser = new JSONParser();
	EditText mojekontohaslo_;
	double lat,lon,latitude = 0;
	double longitude = 0;
	// url to create new product
	private static String url_create_product ="http://opiekuj1.javaprovider.net/php/logowanie.php";
	private static String url_create_product2 ="http://opiekuj1.javaprovider.net/php/rezerwa.php";

	// JSON Node names
	private static final String TAG_SUCCESS = "success";
	private GoogleMap map; private LocationManager locationManager;
	// private LocationManager locationManager;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.gmaps);
		//praca
		 map = ((MapFragment) getFragmentManager()
					.findFragmentById(R.id.map)).getMap();
		 map.setPadding(0, 50, 0, 100);
		 //map.setOnMarkerClickListener(this);
		 Button r=  (Button) findViewById(R.id.btngps);
			//logowanie sie
			r.setOnClickListener(new View.OnClickListener() {
				
				@Override
				public void onClick(View view) {
					// Launching All products Activity
					// TextView chkIos = (TextView) findViewById(R.id.polozenie1);
					// chkIos.setText(String.valueOf(lon));rr("p");
					//Intent i = new Intent(getApplicationContext(), Logowanie.class);
					//startActivity(i);
				//	Intent i = new Intent(getApplicationContext(), Polozenie.class);
				//	startActivity(i);
					 g();
				}
			});
			// Button r1=  (Button) findViewById(R.id.btngps);
				//logowanie sie
			//	r1.setOnClickListener(new View.OnClickListener() {
					
			//		@Override
			//		public void onClick(View view) {
			//			rr("p");
						// Launching All products Activity
						// TextView chkIos = (TextView) findViewById(R.id.polozenie1);
						// chkIos.setText(String.valueOf(lon));
						//Intent i = new Intent(getApplicationContext(), Logowanie.class);
						//startActivity(i);
					//	Intent i = new Intent(getApplicationContext(), Polozenie.class);
					//	startActivity(i);
			//		}
			//	});
				 
			// map.setPadding(0, 50, 0, 100);
			// map.setOnMarkerClickListener(this);
			// map.
			// map.addMarker(new
			// MarkerOptions().position(LOCATION_BURNABY).title("TUT"));

			// Get a handle to the Map Fragment
			// GoogleMap map = ((MapFragment) getFragmentManager()
			// .findFragmentById(R.id.map)).getMap();

			// LatLng sydney = new LatLng(-33.867, 151.206);

			// map.setMyLocationEnabled(true);
			// map.moveCamera(CameraUpdateFactory.newLatLngZoom(sydney, 13));

			// map.addMarker(new MarkerOptions()
			// .title("Sydney")
			// .snippet("The most populous city in Australia.")
			// .position(sydney));
			
	//		addd(50.98138, 18.21434, "mojdom");
	//	addd(51.00274, 18.15491, "smardy");
			// create marker
	/*    if (map != null) {
	        map.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker"));
	    }

	map.setMyLocationEnabled(true);

	locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
	Criteria criteria = new Criteria();
	String bestProvider = locationManager.getBestProvider(criteria, false);
	Location location = locationManager.getLastKnownLocation(bestProvider);
	LocationListener loc_listener = new LocationListener() {

	    public void onLocationChanged(Location l) {}

	    public void onProviderEnabled(String p) {}

	    public void onProviderDisabled(String p) {}

	    public void onStatusChanged(String p, int status, Bundle extras) {}
	};
	location = locationManager.getLastKnownLocation(bestProvider);
	try {
	    lat = location.getLatitude();
	    lon = location.getLongitude();
	} catch (NullPointerException e) {
	    lat = -1.0;
	    lon = -1.0;*/
	}
	//Toast.makeText(this, "Myd"+lat+"-"+lon, Toast.LENGTH_LONG).show();
			/*
			 * 
			 * PolygonOptions rectOptions = new PolygonOptions() .add(new
			 * LatLng(37.35, -122.0), new LatLng(37.45, -122.0), new LatLng(37.45,
			 * -122.2), new LatLng(37.35, -122.2), new LatLng(37.35, -122.0));
			 */

			// Get back the mutable Polygon
			// Polygon polygon = map.addPolygon(rectOptions);

	//	}
	 public void addListenerOnChkIos() {
			
		 TextView chkIos = (TextView) findViewById(R.id.polozenie1);
		 
			chkIos.setOnClickListener(new OnClickListener() {
		 
			  @Override
			  public void onClick(View v) {
					
		                //is chkIos checked?
				/*if (((CheckBox) v).isChecked()) {
					Toast.makeText(MojeDane.this,
				 	   "Bro, try Android :)", Toast.LENGTH_LONG).show();
				}*/
		 
			  }
			});
		 
		  }
	 void pro(){
		 
	 }
	 public void addListenerOnZnajdzMnieNaMapie() {
		 Button r1=  (Button) findViewById(R.id.btnznajdz);
				r1.setOnClickListener(new View.OnClickListener() {
			
					@Override
					public void onClick(View view) {
						 TextView chkIos = (TextView) findViewById(R.id.polozenie1);
						String ulicaWprowadzonaZPalca=chkIos.getText().toString();
						if(ulicaWprowadzonaZPalca==null ||
								ulicaWprowadzonaZPalca=="")
						{
							//brak ulicy
						rr("p");
						}
						else
						{
							//szukanie polozenia i pokaz tego na mapie
							/*String url = "https://maps.googleapis.com/maps/api/geocode/json?";					
							try {
								location = URLEncoder.encode(location, "utf-8");
							} catch (UnsupportedEncodingException e) {
								e.printStackTrace();
							}*/
					//		String address = "address=" + location;
				//			String sensor = "sensor=false";
				//			url = url + address + "&" + sensor;
				//			DownloadTask downloadTask = new DownloadTask();
				//			downloadTask.execute(url);
						}
						// Launching All products Activity
						// TextView chkIos = (TextView) findViewById(R.id.polozenie1);
						// chkIos.setText(String.valueOf(lon));
						//Intent i = new Intent(getApplicationContext(), Logowanie.class);
						//startActivity(i);
					//	Intent i = new Intent(getApplicationContext(), Polozenie.class);
					//	startActivity(i);
					}
				});
		 TextView chkIos = (TextView) findViewById(R.id.polozenie1);
		 
			chkIos.setOnClickListener(new OnClickListener() {
		 
			  @Override
			  public void onClick(View v) {
					
		                //is chkIos checked?
				/*if (((CheckBox) v).isChecked()) {
					Toast.makeText(MojeDane.this,
				 	   "Bro, try Android :)", Toast.LENGTH_LONG).show();
				}*/
		 
			  }
			});
		 
		  }
	 //KONIEC addListenerOnZnajdzMnieNaMapie
	void addd(double a, double b, String c) {
		MarkerOptions marker = new MarkerOptions().position(new LatLng(a, b))
				.title(c);
		map.addMarker(marker);
	}
	void ff(String h){
		  TextView t=(TextView)findViewById(R.id.polozenie); 
	        t.setText(h);
	}
	private String downloadUrl(String strUrl) throws IOException{
        String data = "";
        InputStream iStream = null;
        HttpURLConnection urlConnection = null;
        try{
                URL url = new URL(strUrl);


                // Creating an http connection to communicate with url 
                urlConnection = (HttpURLConnection) url.openConnection();

                // Connecting to url 
                urlConnection.connect();

                // Reading data from url 
                iStream = urlConnection.getInputStream();

                BufferedReader br = new BufferedReader(new InputStreamReader(iStream));

                StringBuffer sb  = new StringBuffer();

                String line = "";
                while( ( line = br.readLine())  != null){
                        sb.append(line);
                }

                data = sb.toString();

                br.close();

        }catch(Exception e){
                Log.d("Exception while downloading url", e.toString());
        }finally{
                iStream.close();
                urlConnection.disconnect();
        }

        return data;
        
	}
	void g(){
		 
		// map.
		// map.addMarker(new
		// MarkerOptions().position(LOCATION_BURNABY).title("TUT"));

		// Get a handle to the Map Fragment
		// GoogleMap map = ((MapFragment) getFragmentManager()
		// .findFragmentById(R.id.map)).getMap();

		// LatLng sydney = new LatLng(-33.867, 151.206);

		// map.setMyLocationEnabled(true);
		// map.moveCamera(CameraUpdateFactory.newLatLngZoom(sydney, 13));

		// map.addMarker(new MarkerOptions()
		// .title("Sydney")
		// .snippet("The most populous city in Australia.")
		// .position(sydney));
		double lat,lon,latitude = 0;
		double longitude = 0;
		addd(50.98138, 18.21434, "mojdom");
	addd(51.00274, 18.15491, "smardy");
		// create marker
    if (map != null) {
        map.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker"));
    }

map.setMyLocationEnabled(true);

locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
String bestProvider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(bestProvider);
LocationListener loc_listener = new LocationListener() {

    public void onLocationChanged(Location l) {}

    public void onProviderEnabled(String p) {}

    public void onProviderDisabled(String p) {}

    public void onStatusChanged(String p, int status, Bundle extras) {}
};
//locationManager.requestLocationUpdates(bestProvider, 0, 0, loc_listener);
location = locationManager.getLastKnownLocation(bestProvider);
try {
    lat = location.getLatitude();
    lon = location.getLongitude();
} catch (NullPointerException e) {
    lat = -1.0;
    lon = -1.0;
}
//Toast.makeText(this, "Myd"+lat+"-"+lon, Toast.LENGTH_LONG).show();
TextView chkIos = (TextView) findViewById(R.id.polozenie1);
chkIos.setText(String.valueOf(lat+" "+lon));
	}
	  void rr(String h){
		  String youraddress="Kluczbork,Jana Pawla II";
		  youraddress=youraddress.replaceAll(" ", "%20");
		  
		  String uri = "http://maps.google.com/maps/api/geocode/json?address="+youraddress+"&sensor=false";
    HttpGet httpGet = new HttpGet(uri);
    HttpClient client = new DefaultHttpClient();
    HttpResponse response;
    StringBuilder stringBuilder = new StringBuilder();

    try {
        response = client.execute(httpGet);
        HttpEntity entity = response.getEntity();
        InputStream stream = entity.getContent();
        int b;
        while ((b = stream.read()) != -1) {
            stringBuilder.append((char) b);
        }
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    JSONObject jsonObject = new JSONObject();
    try {
        jsonObject = new JSONObject(stringBuilder.toString());
        double lat= 0.0, lng= 0.0;
        lng = ((JSONArray)jsonObject.get("results")).getJSONObject(0)
            .getJSONObject("geometry").getJSONObject("location")
            .getDouble("lng");

        lat = ((JSONArray)jsonObject.get("results")).getJSONObject(0)
            .getJSONObject("geometry").getJSONObject("location")
            .getDouble("lat");
        TextView t=(TextView)findViewById(R.id.polozenie); 
        t.setText(String.valueOf(lat+" "+lng));
        //Log.d("latitude", lat);
        //Log.d("longitude", lng);
    } catch (JSONException e) {
        e.printStackTrace();
    }
	      
}
	class CreateNewProductR extends AsyncTask<String,String,String> {

		/**
		 * Before starting background thread Show Progress Dialog
		 * */
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pDialog = new ProgressDialog(Polozenie.this);
			pDialog.setMessage("Rezerwowanie..");
			pDialog.setIndeterminate(false);
			pDialog.setCancelable(true);
			pDialog.show();
		}

		/**
		 * Creating product
		 * */
		protected String doInBackground(String... args) {
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			params.add(new BasicNameValuePair("nazwa", "mm"));
			JSONObject json = jsonParser.makeHttpRequest(url_create_product2,
					"POST", params);
			
			// check log cat fro response
			Log.d("Create Response", json.toString());

			// check for success tag
			try {
				int success = json.getInt(TAG_SUCCESS);

			} catch (JSONException e) {
				e.printStackTrace();
			}

			return null;
		}

		/**
		 * After completing background task Dismiss the progress dialog
		 * **/
		protected void onPostExecute(String file_url) {
			// dismiss the dialog once done
			pDialog.dismiss();
		}

	}
    private class DownloadTask extends AsyncTask<String, Integer, String>{

        String data = null;

        // Invoked by execute() method of this object
        @Override
        protected String doInBackground(String... url) {
                try{                    		
                        data = downloadUrl(url[0]);
                }catch(Exception e){
                         Log.d("Background Task",e.toString());
                }
                return data;
        }

        // Executed after the complete execution of doInBackground() method
        @Override
        protected void onPostExecute(String result){
        		
        		// Instantiating ParserTask which parses the json data from Geocoding webservice
        		// in a non-ui thread
        		ParserTask parserTask = new ParserTask();

                // Start parsing the places in JSON format
                // Invokes the "doInBackground()" method of the class ParseTask
                parserTask.execute(result);
        }

}
	class ParserTask extends AsyncTask<String, Integer, List<HashMap<String,String>>>{
		JSONObject jObject;
		@Override
		protected List<HashMap<String,String>> doInBackground(String... jsonData) {
		
			List<HashMap<String, String>> places = null;			
			GeocodeJSONParser parser = new GeocodeJSONParser();
	    
	        try{
	        	jObject = new JSONObject(jsonData[0]);
	        	
	            /** Getting the parsed data as a an ArrayList */
	            places = parser.parse(jObject);
	            
	        }catch(Exception e){
	                Log.d("Exception",e.toString());
	        }
	        return places;
		}
		
		// Executed after the complete execution of doInBackground() method
		@Override
		protected void onPostExecute(List<HashMap<String,String>> list){			
			
			// Clears all the existing markers		
		//	Polozenie.get()
		//	mMap.clear();
			
			for(int i=0;i<list.size();i++){
			
				// Creating a marker
	            MarkerOptions markerOptions = new MarkerOptions();
	            
	            // Getting a place from the places list
	            HashMap<String, String> hmPlace = list.get(i);

	            // Getting latitude of the place
	            double lat = Double.parseDouble(hmPlace.get("lat"));	            
	            
	            // Getting longitude of the place
	            double lng = Double.parseDouble(hmPlace.get("lng"));
	            
	            // Getting name
	            String name = hmPlace.get("formatted_address");
	            //51.1126321//16.9572143
	            
	            //51.1138632//16.9610666
	            LatLng latLng = new LatLng(lat, lng);
	        //    EditText f=(EditText) findViewById(R.id.et_place);
	        //    f.setText(String.valueOf(lat+" "+lng));
	            //		et_place
	            // Setting the position for the marker
	            markerOptions.position(latLng);
	            
	            // Setting the title for the marker
	            markerOptions.title(name);

	            // Placing a marker on the touched position
	         //   mMap.addMarker(markerOptions);    
	            
	            // Locate the first location
	          //  if(i==0)
	           // 	mMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
	        }            
		}
	}
	/**
	 * Background Async Task to Create new product
	 * */
	class CreateNewProduct1 extends AsyncTask<String,String,String> {

		/**
		 * Before starting background thread Show Progress Dialog
		 * */
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pDialog = new ProgressDialog(Polozenie.this);
			pDialog.setMessage("Logowanie..");
			pDialog.setIndeterminate(false);
			pDialog.setCancelable(true);
			pDialog.show();
		}

		/**
		 * Creating product
		 * */
		protected String doInBackground(String... args) {
			String name = mojekontohaslo_.getText().toString();
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			params.add(new BasicNameValuePair("nazwa", "mm"));
			JSONObject json = jsonParser.makeHttpRequest(url_create_product,
					"POST", params);
			
			// check log cat fro response
			Log.d("Create Response", json.toString());

			// check for success tag
			try {
				int success = json.getInt(TAG_SUCCESS);

				if (success == 1) {
					// successfully created product
					Intent i = new Intent(getApplicationContext(), MojeDane.class);
					startActivity(i);
					
					// closing this screen
					finish();
					//inputDesc =inputPrice =inputName = null;
				} else {
					Intent i = new Intent(getApplicationContext(), MainScreenActivity.class);
					startActivity(i);
					// failed to create product
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}

			return null;
		}

		/**
		 * After completing background task Dismiss the progress dialog
		 * **/
		protected void onPostExecute(String file_url) {
			// dismiss the dialog once done
			pDialog.dismiss();
		}

	}
}

